﻿#region MyJScript - LGPL Copyright (c) 2008 Lionel Laské
//
// This file is part of MyJScript.
//
// MyJScript is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// MyJScript is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with MyJScript; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//
//================================================================================
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting.Runtime;
using MyJScript.Compiler;
using MyJScript.DLR;

namespace MyJScript.Test
{
    class Utils
    {
        /// <summary>
        /// Current script engine
        /// </summary>
        static private ScriptEngine engine;

        /// <summary>
        /// Temp file name
        /// </summary>
        static private List<string> tempFiles = new List<string>();

        /// <summary>
        /// Set up DLR domain manager
        /// </summary>
        public static void Initialize()
        {
            // Load script engine
            engine = ScriptRuntime.Create().GetEngine(typeof(MJSLanguageContext));
        }

        /// <summary>
        /// Delete temp files
        /// </summary>
        public static void Cleanup()
        {
            // Delete temp files
            foreach (string filename in tempFiles)
                File.Delete(filename);
            tempFiles.Clear();

            // Shutdown script engine
            engine.Shutdown();
        }

        /// <summary>
        /// Helper to create a SourceUnit from a string.
        /// </summary>
        /// <param name="src">source code</param>
        /// <returns></returns>
        public static SourceUnit Source(string src)
        {
            // Put source in a temp file
            string filename = Path.GetTempFileName();
            FileStream fs = File.OpenWrite(filename);
            StreamWriter sw = new StreamWriter(fs);
            if (src != null)
                sw.Write(src);
            sw.Close();
            fs.Close();

            // Create source unit
            SourceUnit sourceUnit = engine.CreateScriptSourceFromFile(filename).SourceUnit;

            // Mark file to remove
            tempFiles.Add(filename);

            return sourceUnit;
        }
    }
}
